# -*- coding:utf-8 -*-
import threading,logging,time
from scheduler import Scheduler
from downloader import Downloader
import settings

class Engine(threading.Thread):
    def __init__(self,website):        
        threading.Thread.__init__(self)
        self.threads = []
        self.add_request_lock=threading.Lock()
        self.get_request_lock=threading.Lock()
        self.set_url_mark_lock=threading.Lock()
        self.d_locks={'add_request_lock':self.add_request_lock,
                      'get_request_lock':self.get_request_lock,
                      'set_url_mark_lock':self.set_url_mark_lock}
        
        self.scheduler=Scheduler(self.d_locks)
        
        self.logger=self.ini_log()
    
    def ini_log(self):
        logger = logging.getLogger()
        hdlr = logging.FileHandler(settings.S_log_file)
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        hdlr.setFormatter(formatter)
        logger.addHandler(hdlr)
        logger.setLevel(logging.NOTSET)
        return logger
    
    def run(self):
        print 'ENGINE STSRT'
        self.is_running=True
        for i in range(settings.S_thre_num):
            t=Downloader(i,self.scheduler,self)
            self.threads.append(t)
        
        for t in self.threads:
            t.start()
            time.sleep(3)
            
        for t in self.threads:
            t.join()
        self.stop()
            
    def stop(self):
        self.is_running=False
        self.end()
        
    def end(self):
        print 'ENGINE STOP'
            
if __name__=='__main__':
    eng=Engine('zhidao')
    eng.start()




















